package cn.rocky.other;

import java.util.ArrayList;
import java.util.Random;


import org.openjdk.jmh.annotations.Benchmark;
import org.openjdk.jmh.annotations.BenchmarkMode;
import org.openjdk.jmh.annotations.Mode;
import org.openjdk.jmh.annotations.OutputTimeUnit;
import org.openjdk.jmh.annotations.State;
import org.openjdk.jmh.annotations.Scope;
import org.openjdk.jmh.annotations.Setup;
import org.openjdk.jmh.annotations.TearDown;
import org.openjdk.jmh.annotations.Warmup;
import org.openjdk.jmh.infra.Blackhole;
import org.openjdk.jmh.runner.Runner;
import org.openjdk.jmh.runner.options.Options;
import org.openjdk.jmh.runner.options.OptionsBuilder;


import java.util.concurrent.TimeUnit;

@State(Scope.Thread)
public class ArrayListBenchmark {
    private ArrayList<Integer> arrayList;
    private Random random;
    private final int number = 10;

    @Setup
    public void setup() {
        arrayList = new ArrayList<>();
        random = new Random();
        for (int i = 0; i < number; i++) {
            arrayList.add(random.nextInt(100));
        }
    }

    @TearDown
    public void tearDown() {
        arrayList = null;
        random = null;
    }

    @Benchmark
    @BenchmarkMode(Mode.AverageTime)
    @OutputTimeUnit(TimeUnit.MICROSECONDS)
    @Warmup(iterations = 3)
    public void testAdd(Blackhole bh) {
        arrayList.add(random.nextInt(100));
        bh.consume(arrayList);
    }

    @Benchmark
    @BenchmarkMode(Mode.AverageTime)
    @OutputTimeUnit(TimeUnit.MICROSECONDS)
    @Warmup(iterations = 3)
    public void testGet(Blackhole bh) {
        int index = random.nextInt(number);
        int value = arrayList.get(index);
        bh.consume(value);
    }

    @Benchmark
    @BenchmarkMode(Mode.AverageTime)
    @OutputTimeUnit(TimeUnit.MICROSECONDS)
    @Warmup(iterations = 3)
    public void testRemove(Blackhole bh) {
        int index = random.nextInt(number);
        arrayList.remove(index);
        bh.consume(arrayList);
    }

    public static void main(String[] args) throws Exception{
        Options opt=new OptionsBuilder()
                //导入要测试的类
                .include(ArrayListBenchmark.class.getSimpleName())
                .build();
        new Runner(opt).run();
    }
}

